(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.countryCalendar.createController', createController);
	createController.$inject = ['$rootScope', '$scope', 'Constants', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'countryCalendarService', '$log'];
	function createController($rootScope, $scope, Constants, modalService, gridService, layoutConfig, validatorConfig, authService, countryCalendarService, $log) {
		var ctrl = this, calendarInfo = $scope.$stateParams.params, errorMessage = {};
		var log = $scope.loggerFactory.getLogger("countryCalendarCreate")
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		
		function diffArray(arr1, arr2) {
			if (arr1 != null) {
				if (arr1.length == 1 && arr2 == null) {
					return arr1[0];
				}
				for (var i = 0; i < arr1.length; i++) {
					var findFlag = false;
					for (var j = 0; j < arr2.length; j++) {
						if (arr1[i] == arr2[j]) {
							findFlag = true;
							break;
						}
					}
					if (!findFlag) {
						return arr1[i];
					}
				}
			} 
			return false;
		}
		
		function getDateIndex(date, arr) {
			for (var index = 0; index < arr.length; index++) {
				var eachDate = arr[index];
				if (eachDate.getYear() == date.getYear() && eachDate.getMonth() == date.getMonth() && eachDate.getDate() == date.getDate()) {
					return index;
				}
			}
			return -1;
		}
		
		ctrl.switchNewYearCalendar = function() {
			var calendarYear = ctrl.countryCalendar.calendarDay.year;
			if (!calendarYear) {
				var messages = [];
				messages.push("js.common.calendar.yearshouldbetween1990to2100");
				modalService.openErrorDialogs({
					'messages' : messages
				});
				return;
			}
			if (calendarYear < 1990 ) {
				var messages = [];
				messages.push("js.cda.calendar.yearcannotbeearlierthan1990");
				modalService.openErrorDialogs({
					'messages' : messages
				});
				return;
			}
			if (calendarYear > 2100 ) {
				var messages = [];
				messages.push("js.common.calendar.yearcannotbelaterthan2200");
				modalService.openErrorDialogs({
					'messages' : messages
				});
				return;
			}
			authService.createInit(ctrl.countryCalendar).then(function(response) {				
				ctrl.countryCalendar.calendarDay = response.data.calendarDay ;
				ctrl.countryCalendar.holidays = response.data.holidays;
				ctrl.countryCalendar.weekendDays = response.data.weekendDays;
				$scope.calendarYear = ctrl.countryCalendar.calendarDay.year;
			});
		}
		
		ctrl.init = function() {
			ctrl.countryCalendar = {};	
			ctrl.countryCalendar.calendarDay = {};
			

			$scope.$watch('vm.countryCalendar.weekendDays', function(newValue, oldValue) {
				if (ctrl.countryCalendar.calendarDay) {
					var daystrs;
					var calendarInfo = ctrl.countryCalendar.calendarDay.calendarInfo;
					if ((newValue != null && oldValue!= null && newValue.length > oldValue.length)
							|| (newValue != null && newValue.length == 1 && oldValue == null)) {
							var newWeekday = diffArray(newValue, oldValue);
							if (newWeekday == 'MON') {
								daystrs = calendarInfo[5].split(',');
							} else if (newWeekday == 'TUE') {
								daystrs = calendarInfo[7].split(',');
							} else if (newWeekday == 'WED') {
								daystrs = calendarInfo[9].split(',');
							} else if (newWeekday == 'THU') {
								daystrs = calendarInfo[11].split(',');
							} else if (newWeekday == 'FRI') {
								daystrs = calendarInfo[13].split(',');
							} else if (newWeekday == 'SAT') {
								daystrs = calendarInfo[1].split(',');
							} else if (newWeekday == 'SUN') {
								daystrs = calendarInfo[3].split(',');
							}
							for (var index in daystrs) {
								var date = new Date(Date.parse(daystrs[index].replace(/-/g,   "/")))
								if (getDateIndex(date, ctrl.countryCalendar.holidays) == -1) {
									ctrl.countryCalendar.holidays.push(date);
								}
								
							}
						} else {
							var rmvWeekday = diffArray(oldValue, newValue);
							if (rmvWeekday == 'MON') {
								daystrs = calendarInfo[5].split(',');
							} else if (rmvWeekday == 'TUE') {
								daystrs = calendarInfo[7].split(',');
							} else if (rmvWeekday == 'WED') {
								daystrs = calendarInfo[9].split(',');
							} else if (rmvWeekday == 'THU') {
								daystrs = calendarInfo[11].split(',');
							} else if (rmvWeekday == 'FRI') {
								daystrs = calendarInfo[13].split(',');
							} else if (rmvWeekday == 'SAT') {
								daystrs = calendarInfo[1].split(',');
							} else if (rmvWeekday == 'SUN') {
								daystrs = calendarInfo[3].split(',');
							}
							for (var index in daystrs) {
								var date = new Date(Date.parse(daystrs[index].replace(/-/g,   "/")))
								var index = getDateIndex(date, ctrl.countryCalendar.holidays);
								if (index > -1) {
									ctrl.countryCalendar.holidays.splice(index, 1);
								}
								
							}
						}
					}
			}, true);
			
			
			$scope.$watch('vm.countryCalendar.countryCode', function(newValue, oldValue) {
				ctrl.countryCalendar.calendarCode =  'O:' + newValue;
				ctrl.countryCalendar.calendarName = newValue;
				
			});
			
			countryCalendarService.initOptions($scope, ctrl).then(function() {
				authService.create({}).then(function(response) {				
					ctrl.countryCalendar = response.data ;
					$scope.calendarYear = ctrl.countryCalendar.calendarDay.year;
				});			
			});
		};
		var oldCalendar ;
		ctrl.saveCalendar = function() {
			if (ctrl.countryCalendar.taskId) {
				oldCalendar = {};
				angular.copay(ctrl.countryCalendar, oldCalendar);
				return authService.createContinueSave(ctrl.countryCalendar).then(saveSuccessful, saveFailed);
			} else {
				oldCalendar = {};
				angular.copy(ctrl.countryCalendar, oldCalendar);
				return authService.createSave(ctrl.countryCalendar).then(saveSuccessful, saveFailed);
			}
		};

		ctrl.submitCalendar = function() {
			if (ctrl.countryCalendar.taskId) {
				oldCalendar = {};
				angular.copy(ctrl.countryCalendar, oldCalendar);
				return authService.createContinueSubmit(ctrl.countryCalendar).then(submitSuccessful, submitFailed);
			} else {
				oldCalendar = {};
				angular.copy(ctrl.countryCalendar, oldCalendar);
				return authService.createSubmit(ctrl.countryCalendar).then(submitSuccessful, submitFailed);
			}
		};

		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedSubCommpanyList = selectedRows;
		}

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.countryCalendar.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.countrycalendar.list',
					'state' : 'cda.countryCalendar.list',
					'params' : {}
				}]
			});
		}

		function submitFailed(response) {
			angular.copy(oldCalendar, ctrl.countryCalendar);
			oldCalendar = null;
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			angular.copy(oldCalendar, ctrl.countryCalendar);
			oldCalendar = null;
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);